'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Locale, defaultLocale, getCurrentLocale, setCurrentLocale } from '../i18n';

interface LanguageContextType {
  locale: Locale;
  setLocale: (locale: Locale) => void;
  t: (key: string) => string;
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [locale, setLocale] = useState<Locale>(defaultLocale);
  const [messages, setMessages] = useState<Record<string, unknown>>({});

  // 初始化语言
  useEffect(() => {
    const currentLocale = getCurrentLocale();
    setLocale(currentLocale);
    loadMessages(currentLocale);
  }, []);

  // 加载翻译文件
  const loadMessages = async (newLocale: Locale) => {
    try {
      const messagesModule = await import(`../messages/${newLocale}.json`);
      setMessages(messagesModule.default);
    } catch (error) {
      console.error(`Failed to load messages for locale: ${newLocale}`, error);
      // fallback to English
      if (newLocale !== 'en') {
        const fallbackModule = await import(`../messages/en.json`);
        setMessages(fallbackModule.default);
      }
    }
  };

  // 切换语言
  const handleSetLocale = async (newLocale: Locale) => {
    setLocale(newLocale);
    setCurrentLocale(newLocale);
    await loadMessages(newLocale);
  };

  // 翻译函数
  const t = (key: string): string => {
    const keys = key.split('.');
    let value: unknown = messages;
    
    for (const k of keys) {
      if (value && typeof value === 'object' && value !== null && k in value) {
        value = (value as Record<string, unknown>)[k];
      } else {
        return key; // 返回 key 作为 fallback
      }
    }
    
    return typeof value === 'string' ? value : key;
  };

  return (
    <LanguageContext.Provider value={{ locale, setLocale: handleSetLocale, t }}>
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage() {
  const context = useContext(LanguageContext);
  if (!context) {
    throw new Error('useLanguage must be used within a LanguageProvider');
  }
  return context;
}
